<template>
  <div>
    <el-form :model="goods" :rules="rules" ref="goodsform" label-position="right" label-width="100px" class="goods-form">
      <div class="goods-title">基本信息</div>
      <!-- 基本信息 -->
      <div>
        <el-form-item label="商品标题" class="goods-form-item" prop="name">
          <el-input v-model="goods.name" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">限30个字，60个字符内</div> 
        </el-form-item>
        <el-form-item label="短标题" class="goods-form-item" prop="short_name">
          <el-input v-model="goods.short_name" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">限12个字</div> 
        </el-form-item>
        <el-form-item label="简单说明" class="goods-form-item" prop="simple_info">
          <el-input type="textarea" :rows="1" v-model="goods.simple_info" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">在商品详情页标题下面展示卖点信息，200字以内</div> 
        </el-form-item>
        <el-form-item label="商品货号" class="goods-form-item">
          <el-input v-model="goods.code" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item label="分类" class="goods-form-item">
          <div style="width: 50%;">
            <el-select v-model="firstGroupId" placeholder="选择一级分类" style="width: calc(50% - 8px)" size="small" @change="selectGoodsGroup">
              <el-option :label="item.name" :value="item.id" v-for="item in goodGroupList" :key="item.id"></el-option>             
            </el-select>
            <el-select v-model="goods.category_id" placeholder="选择二级分类" style="width: calc(50% - 8px);margin-left:10px" size="small"
              v-if="firstGroup.length>0">
              <el-option :label="item.name" :value="item.id" v-for="item in firstGroup" :key="item.id"></el-option>             
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="增值服务" class="goods-form-item">
          <div style="width:50%;display:inline-flex">
            <el-input v-model="labels[index]" :style="{flex: 1, 'margin-left': index === 0 ? '0' : '15px'}" placeholder="请输入" size="small" v-for="(item, index) in labels" :key="index"></el-input>
          </div>          
          <div class="goods-form-item-text">显示在店铺信息下方，最多4个，每个最多4个字</div> 
        </el-form-item>
        <el-form-item label="商品主图" class="goods-form-item" prop="pic_urls">
          <el-button type="primary" plain @click="openMainPicPanel" size="small">选择图片</el-button>
          <div class="goods-form-item-text" style="width:calc(100% - 150px)">建议尺寸：750×750，最多上传5张，支持png、jpg、jpeg格式，大小不超过500KB</div> 
        </el-form-item>
        <el-form-item class="goods-form-item" v-if="mainPicList.length>0">
          <l-pic v-for="(item,index) in mainPicList" :key="index"
            :picurl="item"
            :pickey="index"
            :picdata="item"
            :picmargin="'-20px 10px 10px 10px'"
            :size="{ width:80, height:80 }"
            :piclist="mainPicList"
            @delPic="delMainPic"/>
        </el-form-item>
      </div>

      <div class="goods-title">商品详情</div>
      <!-- 商品详情 -->
      <div style="padding: 10px 20px">
        <tinymce v-model="goods.detail_info" :height="300" width="100%" /> 
      </div>

      <div class="goods-title">价格规格库存</div>
      <!-- 价格规格库存 -->
      <div>

        <el-form-item label="商品积分" class="goods-form-item" prop="score">
          <el-input v-model="goods.score" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
        <el-form-item label="库存" class="goods-form-item" prop="stocks">
          <el-input v-model="goods.stocks" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
      </div>

      <div class="goods-title">其他信息</div>
      <!-- 其他信息 -->
      <div>
        <el-form-item label="首页展示" class="goods-form-item">
          <el-switch v-model="goods.is_top"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="排序" class="goods-form-item">
          <el-input v-model="goods.sort" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
      </div>
    </el-form>

    <div style="text-align: center;margin-top:50px">
      <el-button type="primary" style="padding:10px 30px;font-weight:600" @click="submit">提 交</el-button>
    </div>

    <!-- 相册面板 -->
    <Modal v-model="disPicPanel" width="1128" :footer-hide="true">
      <photo-album v-if="disPicPanel" :maxcount="maxPicCount" @selectPicData="getPicData"/>
    </Modal>
  </div>
</template>

<script>
import { rules, upDateFormat } from './goodsData' 
import { getScoreGoodsList, postScoreGoods, putGoods } from '@/api/score'
import PhotoAlbum from '@/components/PhotoAlbum'
import LPic from '@/components/lPic'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'Entity',
  components: {
    PhotoAlbum,
    LPic,
    Tinymce
  },
  props: {
    goods: {
      type: Object,
      required: true
    },
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // goods: { key: this.$store.state.app.activeApp.saa_key, ...goods },
      rules: rules,

      goodGroupList: [], //商品分组
      firstGroup: [],//一级分类
      firstGroupId: '',//选择的一级分类的ID
      
      goodsAreaList: [],//商品销售区域
      
      labels: [ '', '', '', '' ],

      disPicPanel: false, //打开相册面板
      maxPicCount: 5,//最多选择图片张数

      mainPicList: this.goods.pic_urls.split(',').filter(item => item !== ''),//商品主图列表

      groupTypeList:[{ assemble_number: '', assemble_group_discount: '', discount: '' }],

      other: '1'
    }
  },
  watch: {
    goodGroupList(newValue) { //商品分组
      // console.log(newValue.length);
      if(newValue.length > 0) {
        this.firstGroupId = newValue[0].id;
        this.selectGoodsGroup();
      }
    },
    labels(newValue) { //增值服务
      this.goods.label = ''
      newValue.forEach((item,index) => {
        if(item.trim() !== ''){
          if(index < 3){
            this.goods.label += item + ','
          }else{
            this.goods.label += item
          }          
        }
      });
    },
    mainPicList(newValue) { //商品主图
      if(newValue.length === 0) {
        this.goods.pic_urls = '';
      }else{
        newValue.forEach((item,index) => {
          if(index < 4){
            this.goods.pic_urls += item + ',';
          }else{
            this.goods.pic_urls += item;
          }
        })
      }
    },
  },
  mounted() {
    this.getGoodGroup();//获取商品分组

    //设置labels
    this.labels = this.goods.label.split(',');
    for (let index = this.labels.length; index < 4; index++) {
      this.labels[index] = '';       
    }

    //设置商品主图
    this.mainPicList = [];
    this.goods.pic_urls.split(',').forEach(item => {
      if(item !== '' && item !== null && item !== undefined){
        this.mainPicList.push(item);
        this.maxPicCount --;
      }
    })
  },
  methods: {
    /**
     * 提交
     */
    submit() {
      this.$refs.goodsform.validate(valid => {
        if(valid) {
          if (this.isAdd) {
            postScoreGoods(this.goods).then(res => {
              if(res.status === 200) {
                this.$message.success('添加成功！');
                this.$router.push('/score/list');
              }else{
                this.$message.error(res.message);
              }
            })
          }else{
            const params = {key: this.$store.state.app.activeApp.saa_key, ...upDateFormat(this.goods)};
            putGoods(params).then(res => {
              if(res.status === 200) {
                this.$message.success('修改成功！');
                this.$router.push('/score/list');
              }else{
                this.$message.error(res.message);
              }
            })
          }
        }else {
          this.$message.error('请根据提示，完善商品信息！')
        }
      })
    },
    /**
     * 获取商品分组
     */
    getGoodGroup() {
      getScoreGoodsList({ key: this.$store.state.app.activeApp.saa_key }).then(res => {
        if(res.status === 200){
          this.goodGroupList = res.data;
        }else if(res.status === 204){
          this.goodGroupList = []
        }else{
          this.$message.error(res.message);
        }
      })
    },
    /**
     * 选择商品分类
     */
    selectGoodsGroup() {
      const group = this.goodGroupList.find(item => item.id === this.firstGroupId);
      this.firstGroup = group === undefined ? [] : group.data;
      if(this.firstGroup.length > 0){
        this.goods.category_id = this.firstGroup[0].id;
      }else{
        this.goods.category_id = this.firstGroupId;
      }
    },
    /**
     * 打开主图选择面板
     */
    openMainPicPanel() {
      if(this.maxPicCount > 0){
        this.disPicPanel = true;
      }else{
        this.$message.warning(`最多可选择5张图片，已选择${5-this.maxPicCount}张,不可选择`);
      }
    },
    /**
     * 获取选择到的主图数据
     */
    getPicData(data) {
      this.disPicPanel = false;
      data.forEach(item => {
        if(this.maxPicCount > 0) {
          this.mainPicList.push(item.pic_url);
          this.maxPicCount --;
        }else{
          this.$message.warning(`最多可选择5张图片，已选择${5-this.maxPicCount}张`);
          return false
        }
      })
    },
    /**
     * 删除主图
     */
    delMainPic(data) {
      
      this.mainPicList.splice(this.mainPicList.findIndex(item => item===data),1);
      this.maxPicCount++;
    },
    /**
     * 显示添加属性值输入框
     */
    showPropInput(index) {
      this.isPropInput = true;
      this.propEditIndex = index;
      this.$nextTick(() => {
        this.$refs.savePropInput[0].$refs.input.focus();
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.goods-form{

}
.goods-title{
  height: 47px;
  width: 100%;
  line-height: 47px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 2px;
  color: #8f8f8f;
  padding: 0 10px;
  background-color: #F4F8FB;
}
.goods-form-item{
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding: 5px 0;
  box-sizing: border-box;
  &-input{
    width: 50%;
    height: 40px;
    line-height: 40px;
  }
  &-text{
    width: calc(50% - 100px);
    display: inline-block;
    height: 40px;
    line-height: 40px;
    padding: 0 0 0 20px;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
  }
  &-button-text{
    width: calc(100% - 200px);
    display: inline-block;
    height: 40px;
    line-height: 40px;
    padding: 0 0 0 20px;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
  }
  &-button{
    padding: 5px 10px;
    margin-left: 10px;
  }
  &-video{
    height: 150px;
    min-width: 200px;
    max-width: 100%;
  }
}

.group-type{
  width:calc(100% - 100px);
  display: inline-flex;
  &>div{
    flex: 1;
    padding-right: 10px;
  }
  &-title{
    // flex: 1;
    width: 80px;
    display: inline-block;
    padding: 0 5px 0 0;
    color: #909399;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
    // text-align: right;
  }
  &-input{
    width: calc(100% - 120px);
    height: 40px;
    line-height: 40px;
  }
  &-text{
    width: 100%;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
}
.cutprice-col{
  overflow:hidden;
  height: 40px;
}
.cutprice-title{
  width: 70px;
  display: inline-block;
  padding: 0 5px 0 0;
  color: #909399;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  vertical-align: middle;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.prop-table{
  border: 1px dashed #eee;
  text-align: center;
  &-header{
    height: 30px;
    line-height: 30px;
    background-color: #F4F8FB;
  }
  &-row{
    height: 60px;
    line-height: 60px;
    &-col{
      height: 60px;
    }
  }
}
.img-box-button{
  height: 50px;
  width: 50px;
  border: 2px dashed #eee;
  border-radius: 4px;
  margin: 5px auto;
  cursor: pointer;
}
</style>